{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 长度为M的序列中找到最大或最小的N个元素\n",
    "- 与M相比，N较小"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-4\n",
      "[42, 37]\n",
      "[1, 2]\n"
     ]
    }
   ],
   "source": [
    "import heapq\n",
    "nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]\n",
    "heap = list(nums)\n",
    "heapq.heapify(heap)                # 数组转为堆\n",
    "print(heapq.heappop(heap))         # 弹出最小值(堆顶)\n",
    "heapq.heappush(heap, 9)            # 堆中增加元素\n",
    "print(heapq.nlargest(2, heap))     # 最大的2个数\n",
    "print(heapq.nsmallest(2, heap))    # 最小的两个数\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 与M相比, N较大"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-4, 1]\n",
      "[37, 42]\n"
     ]
    }
   ],
   "source": [
    "nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]\n",
    "print(sorted(nums)[:2])\n",
    "print(sorted(nums)[-2:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<br>\n",
    "实际上都是用heapq即可，因为nlargest和nsmallest这两个方法会根据情况选择最优解法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit",
   "language": "python",
   "name": "python37464bit0eab7a6caf29454899b876d50238c56e"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
